# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address
from common.utils.tz import local_now
from common.cache import redis_cache

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'spin41054977s1na1l5q': {
        # 信通支付 银联快捷  费率1.41% 10---5000 dwc
        'API_KEY': '6FVRNAUBEK0YQ8GC',
        'gateway': 'http://47.75.55.162:28633/rb/pay',
        'query_gateway': 'http://47.75.55.162:28633/rb/queryOrder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pay_type(service):
    if service == 'unionpay':
        return 'BANK'
    elif service == 'alipay':
        return 'ALIPAY'
    elif service == 'wechat':
        return 'WXPAY'
    else:
        return 'BANK'


def _get_sub_pay_type(service):
    if service == 'unionpay':
        return 'BANK_QUICK'
    elif service == 'alipay':
        return 'ALIPAY_TRANS2BANKCARD'
    elif service == 'wechat':
        return 'WXPAY_H5'
    else:
        return 'BANK_QUICK'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_sign(parameter, api_key):
    '''  生成下单签名 '''
    for key in parameter.keys():
        if not parameter.get(key):
            del parameter[key]
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s|' % (parameter[k])
    s += api_key
    _LOGGER.info("xintongpay sign str: %s", s)
    return _gen_sign(s)


def _gen_sign(s):
    sha256 = hashlib.sha256()
    sha256.update(s.encode('utf8'))
    return sha256.hexdigest().lower()


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xintongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('xintongpay sign not pass, data: %s' % params)


def _build_query_string(params):
    s = ''
    for k in params.keys():
        s += '%s=%s&' % (k, params[k])
    return s[:-1]


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('spId', app_id),
        ('payType', _get_pay_type(service)),
        ('paySubType', _get_sub_pay_type(service)),
        ('amount', str(int(pay_amount * 100))),
        ('spTradeId', str(pay.id)),
        ('callbackUrl', '{}/pay/api/{}/xintongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('frontUrl', ''),
        ('clientIp', _get_device_ip(info)),
        ('spUserId', pay.user_id)
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("xintongpay create data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['spTradeId'])
    url = _get_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    _LOGGER.info("xintongpay create URL : %s", url)
    response = requests.get(url)
    _LOGGER.info("xintongpay create rsp : %s", response.text)
    resp = json.loads(response.text)
    pay_url = resp.get('data').get('jumpUrl')
    return {'charge_info': pay_url}


# SUCCESS
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    _LOGGER.info("xintongpay notify data: %s", data)
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['spTradeId']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("xintongpay fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('xintongpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('xintongpay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('xintongpay pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['tradeState'])
    trade_no = str(data['bcTradeId'])
    total_fee = float(data['payAmount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    """
    TRADE_STATE_PREPARE  未付款
    TRADE_STATE_PAYING   支付中
    TRADE_STATE_END1     已付款
    TRADE_STATE_END2     已退款
    TRADE_STATE_TRASHED  已作废
    """
    _LOGGER.info('xintongpay notify status, trade_status:%s' % trade_status)
    if trade_status == 'TRADE_STATE_END1':
        _LOGGER.info('xintongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('spId', app_id),
        ('bcTradeId', ''),
        ('spTradeId', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("xintongpay query data: %s, order_id is: %s", parameter_dict, parameter_dict['spTradeId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("xintongpay query rsp data: %s", response.text)
    if response.status_code == 200:
        resp = json.loads(response.text)
        data = resp.get('data')
        trade_status = str(data['tradeState'])
        trade_no = str(data['bcTradeId'])
        total_fee = float(data['payAmount']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == 'TRADE_STATE_END1':
            _LOGGER.info('xintongpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('xintongpay data error, status_code: %s', response.status_code)
